import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  message,
  Divider, Modal,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UpdateForm from './createFrom';
import DescView from './descView';
import styles from '../UserManage.less';
import { powerBtnFunc } from '@/utils/utils';

const Option = Select.Option;
const FormItem = Form.Item;
const confirm = Modal.confirm;

/* eslint react/no-multi-comp:0 */
@connect(({ accountModels, loading }) => ({
  accountModels,
  loading: loading.models.accountModels,
}))

@Form.create()
class DeptManage extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    lookDescView: false,
    selectedRows: {},
    formValues: {},
    pagination: {
      pageNo: 1,
      pageSize: 15,
    },
  };


  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { dispatch } = this.props;
    //请求部门列表
    dispatch({
      type: 'accountModels/fetch',
      payload: {},
    });


  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;


    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
    };

    dispatch({
      type: 'accountModels/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'accountModels/fetch',
      payload: {},
    });
  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  //搜索
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'accountModels/fetch',
        payload: values,
      });
    });
  };
  //新建显示窗口
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
      updateModalVisible: !!flag,
      selectedRows: {},
    });
  };
  //修改
  handleUpdateModalVisible = (flag, record) => {
    const { dispatch } = this.props;
    let _this = this;
    let show = _this.setState({
      updateModalVisible: !!flag,
      modalVisible: !flag,
      selectedRows: record,
      formVals: record,
    });
    if (flag) {
      dispatch({
        type: 'accountModels/getDesc',
        payload: { code: record.accountNo },
        callback() {
          show;
        },
      });
    } else {
      show;
    }
  };
  //查看
  handleLookDesc = (flag, record) => {
    console.log(record);
    const { dispatch } = this.props;
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        dispatch({
          type: 'accountModels/getDesc',
          payload: { code: record.accountNo },
        });
      }
    });
  };
  //新建请求
  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'accountModels/add',
      payload: fields,
      callback: (response) => {
        dispatch({
          type: 'accountModels/fetch',
        });
        this.handleModalVisible(false);
      },
    });

  };
  //修改请求
  handleUpdate = fields => {
    const { pagination } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'accountModels/update',
      payload: fields,
      callback: (response) => {
        dispatch({
          type: 'accountModels/fetch',
          payload: pagination,
        });
        this.handleUpdateModalVisible(false, []);
      },
    });
  };
  handleDel = (row) => {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    confirm({
      title: `确定`,
      content: `你确定删除该账户吗?`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'accountModels/remove',
          payload: {
            key: row.accountNo,
          },
          callback: (res) => {
            if (res.code === 200) {
              message.success('删除成功');
              dispatch({
                type: 'accountModels/fetch',
                payload: pagination,
              });
            } else {
              message.error(res.errMsg);
            }
          },
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });

  };
  handleStatus = (row) => {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    Modal.confirm({
      title: `确定`,
      content: `你确定${row.status === 1 ? '停用' : '启用'}该账户吗?`,
      okText: '确认',
      cancelText: '取消',
      onOk() {
        dispatch({
          type: 'accountModels/status',
          payload: {
            accountNo: row.accountNo,
            status: row.status === 1 ? 2 : 1,
          },
          callback: (res) => {
            if (res.code === 200) {
              message.success('操作成功');
              dispatch({
                type: 'accountModels/fetch',
                payload: pagination,
              });
            } else {
              message.error(res.errMsg);
            }
          },
        });
      },
    });
  };

  renderSimpleForm() {
    const { form: { getFieldDecorator } } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="企业名称">
              {getFieldDecorator('enterpriseName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="手机号">
              {getFieldDecorator('mobile')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="用户名称">
              {getFieldDecorator('entUserName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>
      </Form>
    );
  }


  render() {
    const { accountModels: { data, setDesc }, loading } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, lookDescView } = this.state;

    const columns = [
      {
        title: '账户编号',
        dataIndex: 'accountNo',
      },

      {
        title: '企业名称',
        dataIndex: 'enterpriseName',
      },

      {
        title: '用户名称',
        dataIndex: 'userName',
      },

      {
        title: '手机号',
        dataIndex: 'mobile',
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: val => <span>{val === 1 ? '启用' : '停用'}</span>,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            {
              powerBtnFunc('100133',
                [<a key={'edit'} onClick={() => this.handleUpdateModalVisible(true, record)}>修改</a>,
                  <Divider key={'Divider'} type="vertical"/>],
              )
            }

            {
              powerBtnFunc('100134',
                [<a key={'status'} onClick={() => this.handleStatus(record)}>{record.status === 1 ? '停用' : '启用'}</a>,
                  <Divider key={'Divider'} type="vertical"/>],
              )
            }
            {
              powerBtnFunc('100135',
                [<a key={'del'} onClick={() => this.handleDel(record)}>作废</a>,
                  <Divider key={'Divider'} type="vertical"/>],
              )
            }
            {
              powerBtnFunc('100130',
                <a key={'view'} onClick={() => this.handleLookDesc(true, record)}>查看</a>,
              )}
          </Fragment>
        ),
      },
    ];

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };

    return (
      <PageHeaderWrapper title="账户管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              {
                powerBtnFunc('100132',
                  <Button icon="plus" key={'create'} type="primary" onClick={() => this.handleModalVisible(true)}>
                    新增
                  </Button>)
              }
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data ? data : []}
              rowKey={'accountNo'}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <DescView handleLookDesc={this.handleLookDesc}
                  selectedRows={setDesc ? setDesc : {}}
                  lookDescView={lookDescView}/>
        <UpdateForm
          {...parentMethods}
          updateModalVisible={updateModalVisible}
          modalVisible={modalVisible}
          values={setDesc ? setDesc : ''}
          data={data}
        />

      </PageHeaderWrapper>
    );
  }
}

export default DeptManage;
